package com.wendy.service.impl;

import com.alibaba.fastjson.JSON;
import com.wendy.config.FileConfig;
import com.wendy.mapper.AuthorityMapper;
import com.wendy.mapper.RoleMapper;
import com.wendy.mapper.UserMapper;
import com.wendy.model.User;
import com.wendy.service.UserService;
import com.wendy.utils.AlgorithmUtil;
import com.wendy.utils.FileUtil;
import com.wendy.utils.ResponseUtil;
import com.wendy.web.response.ResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

/**
 * @author zhuwending
 */
@Service
@Slf4j
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private FileConfig fileConfig;
    @Autowired
    private AuthorityMapper authorityMapper;

    @Override
    public User selectUserForLogin(String username, String password) {
        password = AlgorithmUtil.md5(password);
        return userMapper.selectUserForLogin(username, password);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper register(User user) {
        if (null == user.getUsername()) {
            return ResponseUtil.errorResponse("用户名不能为空");
        }
        if (null == user.getPassword() || null == user.getRepeatPassword()) {
            return ResponseUtil.errorResponse("密码不能为空");
        }
        if (!user.getRepeatPassword().equals(user.getPassword())) {
            return ResponseUtil.errorResponse("两次输入密码不一致");
        }
        user.setPassword(AlgorithmUtil.md5(user.getPassword()));
        int row = insert(user);
        if (row != 1) {
            return ResponseUtil.errorResponse("注册失败");
        }
        return ResponseUtil.successResponse("注册成功");
    }

    @Override
    public ResponseWrapper uploadPortrait(HttpServletRequest request, MultipartFile file) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (null == user) {
            return ResponseUtil.errorResponse("登录失效，请重新登录");
        }
        if (null == file || file.isEmpty()) {
            return ResponseUtil.errorResponse("文件为空");
        }
        String fileName = FileUtil.getFileNameOnly(file);
        if (StringUtils.isBlank(fileName)) {
            return ResponseUtil.errorResponse("未获取到文件名");
        }
        String suffix = FileUtil.getFileSuffix(file);
        if (StringUtils.isBlank(suffix)) {
            return ResponseUtil.errorResponse("未获取到文件后缀");
        }
        if (!fileConfig.getPictureSuffix().contains(suffix.toLowerCase())) {
            return ResponseUtil.errorResponse("请选择" + fileConfig.getPictureSuffix().toString() + "格式的图片上传");
        }
        fileName = AlgorithmUtil.md5(fileName + System.currentTimeMillis()) + "." + suffix;
        String savePath = fileConfig.getSavePath() + "portrait";
        String showPath = fileConfig.getShowPath() + "portrait";
        try {
            if (!FileUtil.uploadFile(file, savePath, fileName)) {
                return ResponseUtil.errorResponse("上传文件失败");
            }
        } catch (IOException e) {
            log.error("upload file error", e);
        }
        user.setAvatar(showPath + File.separator + fileName);
        int row = update(user);
        if (row != 1) {
            return ResponseUtil.errorResponse("保存图片信息失败");
        }
        session.setAttribute("user", user);
        return ResponseUtil.successResponse("url", showPath + File.separator + fileName, "上传成功");
    }

    @Override
    public void compressPicture(HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (null == user) {
            throw new Exception();
        }
        String file = fileConfig.getSavePath() + "portrait" + File.separator + user.getAvatar().substring(user.getAvatar().lastIndexOf("/") + 1);
        Thumbnails.of(file).size(64, 64).toFile(file);
    }

    @Override
    public ResponseWrapper login(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (StringUtils.isBlank(username)) {
            return ResponseUtil.errorResponse("用户名不能为空");
        }
        if (StringUtils.isBlank(password)) {
            return ResponseUtil.errorResponse("密码不能为空");
        }
        User user = selectUserForLogin(username, password);
        if (null == user) {
            return ResponseUtil.errorResponse("用户名或者密码错误");
        }
        HttpSession session = request.getSession();
        session.setAttribute("user", user);
        session.setMaxInactiveInterval(1000 * 60 * 30);
        String json = JSON.toJSONString(user);
        return ResponseUtil.successResponse("token", AlgorithmUtil.md5(json), "登录成功");
    }

    @Override
    public User selectUserByUsername(String username) {
        if (StringUtils.isBlank(username)) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        User user = userMapper.selectUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        return user;
    }
}
